﻿using System;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GC_RF.Domain.Enums;
using GC_RF.Site.Abstractions;
using GC_RF.Site.Controllers;
using GC_RF.Site.Resources;

namespace GC_RF.Site.Attributes
{
	public class UserAuthorize : AuthorizeAttribute
	{
		public UserRole UserRoles { get; set; }

		protected override bool AuthorizeCore(HttpContextBase httpContext)
		{
			if (httpContext == null)
				throw new ArgumentNullException("httpContext");
			if (!httpContext.User.Identity.IsAuthenticated || AppContext.Current.CurrentUser == null)
				return false;
			return UserRoles.HasFlag((UserRole) AppContext.Current.CurrentUser.RoleId);
		}

		protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
		{
			if (filterContext == null) return;
			SetFilterResult(filterContext);
		}

		protected static void SetFilterResult(AuthorizationContext filterContext)
		{
			if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
				filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.NoContent);
			else
				filterContext.Result = BaseController.RedirectToAction<HomeController>(c => c.Index());
		}
	}
}